/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */
package org.ipig.commons.codec.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.springframework.stereotype.Component;

/**
 * 通用kryo编码解码器
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $Id: GenericKryoCodec.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $
 * @since 1.0
 */
@Component
public class GenericKryoCodec extends AbstractKryoCodecService {
    /**
     * 使用引用
     */
    private final boolean useReferences;

    /**
     * structure
     */
    public GenericKryoCodec() {
        super();
        this.useReferences = true;
    }

    /**
     * structure
     *
     * @param useReferences boolean
     */
    public GenericKryoCodec(boolean useReferences) {
        super();
        this.useReferences = useReferences;
    }

    /**
     * @param kryo   Kryo
     * @param object Object
     * @param output Output
     */
    @Override
    protected void doEncode(Kryo kryo, Object object, Output output) {
        kryo.writeObject(output, object);
    }

    /**
     * @param kryo  Kryo
     * @param input Input
     * @param type  Class<T>
     * @return <T>
     */
    @Override
    protected <T> T doDecode(Kryo kryo, Input input, Class<T> type) {
        return kryo.readObject(input, type);
    }

    /**
     * @param kryo
     */
    @Override
    protected void setKryoInstance(Kryo kryo) {
        kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
        kryo.setReferences(this.useReferences);
    }
}
